package tuling.netty.splitpacket;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import tuling.netty.splitpacket.encoding.RgsCustomizeDecode;
import tuling.netty.splitpacket.encoding.RgsCustomizeEncode;

/**
 * @author RenGaoshuai
 * @date 2023/11/30 9:39
 * @description 要求实现： 先模拟客户端快速发送多条重复的消息，模拟分包粘包
 * 使用自定义分隔符解决分包粘包问题
 * 使用指定报文长度方式解决分包粘包
 */
public class SplitPacketClient {

    public static void main(String[] args) {
        NioEventLoopGroup group = new NioEventLoopGroup();

        try {

            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ChannelPipeline pipeline = socketChannel.pipeline();
//                            //自定义分隔符
//                            pipeline.addLast("delimit", new DelimiterBasedFrameDecoder(1024, Unpooled.copiedBuffer("_".getBytes())));
//
//                            //向pipeline加入编解码器
//                            pipeline.addLast("decoder", new StringDecoder());
//                            pipeline.addLast("encoder", new StringEncoder());

                            //自定义粘包处理
                            pipeline.addLast("rgsCustomizeEncoder", new RgsCustomizeEncode());
                            pipeline.addLast("rgsCustomizeDecoder", new RgsCustomizeDecode());
                            pipeline.addLast(new SplitPacketClientHandler());
                        }
                    });

            System.out.println("client start success");

            ChannelFuture cf = bootstrap.connect("127.0.0.1", 9000).sync();
            Channel channel = cf.channel();

            //连续发送100次，由于tcp是流式数据，内部存在缓冲区，无法确知。
            //两种方法“消息两端增加特殊字符分割”  “指定消息报文的大小”
            for (int i = 0; i < 100; i++) {
                channel.writeAndFlush("在这个温暖的春日里，阳光洒落在嫩绿的树叶上，微风吹过，带来一丝清凉。" + "_");
            }

            cf.channel().closeFuture().sync();


        } catch (InterruptedException e) {
            e.printStackTrace();
            System.out.println(" client interrupted exception");
        } finally {

            group.shutdownGracefully();
        }

    }
}
